package com.hardydou.framework.datasource;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.security.core.parameters.P;

import javax.sql.DataSource;

/**
 * @author ：hardy
 * @description：
 * @date ：Created in 2020/7/15
 * @Copyright ：Hardydou.com
 */
@Configuration
@MapperScan(basePackages = SystemDataSourceConfig.PACKAGE, sqlSessionTemplateRef = SystemDataSourceConfig.SST)
public class SystemDataSourceConfig {

    final static String mod = "system";
    final static String PROTOTYPE = "spring.datasource.druid." + mod;
    final static String PACKAGE = "com.hardydou." + mod + ".mapper";
    final static String MAPPER_PATH = "classpath:mapper/" + mod + "/*Mapper.xml";

    final static String DS = mod + "_dataSource";
    final static String SSF = mod + "_SqlSessionFactory";
    final static String DSTM = mod + "_transactionManager";
    final static String SST = mod + "_SqlSessionTemplate";

    @Bean(name = DS)
    @ConfigurationProperties(PROTOTYPE)
    @Primary
    public DataSource createDataSource() {
        return DruidDataSourceBuilder.create().build();
    }


    @Bean(name = SSF)
    @Primary
    public SqlSessionFactory createSqlSessionFactory(@Qualifier(DS) DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_PATH));
        return bean.getObject();
    }


    @Bean(name = DSTM)
    @Primary
    public DataSourceTransactionManager createTransactionManager(@Qualifier(DS) DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = SST)
    @Primary
    public SqlSessionTemplate createSqlSessionTemplate(@Qualifier(SSF) SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
